<template>
  <base-view :model="query" @submit="search" class="custom">
    <template v-slot:params>
      <a-col :span="8">
        <a-form-model-item label="二维码批次号">
          <a-input v-model="query.qrCodeBatchNo" placeholder="请输入二维码批次号" />
        </a-form-model-item>
      </a-col>
      <a-col :span="24">
        <a-form-model-item class="search">
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </a-form-model-item>
      </a-col>
    </template>
    <div class="section">
      <div class="btn-group">
        <a-button type="primary" @click="openModal">批量生产二维码</a-button>
        <a-button type="primary" @click="exportExcel">导出</a-button>
      </div>
      <a-row :gutter="20">
        <a-col span="12">
          <a-table :scroll="{ x: 1100 }" :columns="patchColumns" :customRow="rowClick" :dataSource="batchDataSource"
            :rowKey="(record, index) => { return index }" :loading="loading" :pagination="patchPagination"
            @change="patchPageChange" @showSizeChange="patchPageChange"
            :rowSelection="{ hideDefaultSelections: true, selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio' }">
          </a-table>
        </a-col>
        <a-col span="12">
          <a-table ref="table" :columns="columns" :dataSource="dataSource" rowKey="id" :loading="loading"
            @change="pageChange" @showSizeChange="pageChange" :pagination="pagination" :scroll="{ x: 1500 }">
            <template slot="operation" slot-scope="text, record">
              <!-- <a-popconfirm title="确定停用？" v-if="record.qrStatus === '00' && record.bindStatus === '01'" -->
              <a-popconfirm title="确定停用？" v-if="record.qrStatus === '00'"
                @confirm="changeStatus(record, 'stop')" okText="确定" cancelText="取消">
                <a-icon type="stop" :style="{ fontSize: '14px',marginRight: '6px' }" theme="twoTone" twoToneColor="#4a9ff5" title="停用"></a-icon>
              </a-popconfirm>

              <a-popconfirm title="确定启用？" v-if="record.qrStatus === '01'" @confirm="changeStatus(record, 'use')"
                okText="确定" cancelText="取消">
                <a-icon type="check-circle" :style="{ fontSize: '14px',marginRight: '6px' }" theme="twoTone" twoToneColor="#4a9ff5" title="启用"></a-icon>
              </a-popconfirm>
              <a-icon type="eye" :style="{ fontSize: '16px'}" @click="view(record)" theme="twoTone" twoToneColor="#4a9ff5" title="查看"></a-icon>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>
    <!--批量生成二维码页面-->
    <a-modal :maskClosable="false" v-model="modalVisible" title="批量生成二维码" width="800px" @ok="confirmSubmit">
      <div class="modal">
        <a-form-model ref="modalForm" :rules="rules" :model="beanInfo">
          <a-form-model-item label="生成二维码数量" prop="qrCodeNum">
            <a-input-number v-model="beanInfo.qrCodeNum" placeholder="最大允许输入3000" :min="0" :max="3000"
              style="width: 100%" :precision="0"></a-input-number>
          </a-form-model-item>
        </a-form-model>
      </div>
    </a-modal>
    <!--导出，查看页面-->
    <a-modal :maskClosable="false" v-model="exportModalVisible" :title="exportOrViewTitle" @ok="submitQRCode" width="1000px">
      <div class="modal">
        <div class="form-wrapper">
          <entity-view ref="qrcodeModalForm" :model="qrcodeInfo" @submit="submitQRCode" formItemWidth="100%">
            <form-item label="二维码代码">
              <div>{{qRcode}}</div>
            </form-item>
            <form-item label="二维码样式" prop="qrCodeStyle" v-model="qrcodeInfo.qrCodeStyle" input-type="radioGroup"
              :options="exportOrViewOption">
            </form-item>
            <form-item label="分辨率" v-if="qrcodeInfo.qrCodeStyle === '00'" prop="imgResolution"
              v-model="qrcodeInfo.imgResolution" input-type="radioGroup" :options="[
                { label: '普通(350*340)', value: '00' },
                { label: '高清(1024*1034)', value: '01' },
              ]"></form-item>
            <form-item label="背景色" v-if="qrcodeInfo.qrCodeStyle === '00'" prop="colorStyle">
              <a-radio-group v-model="qrcodeInfo.colorStyle" :options="[
                { label: '蓝色', value: 'blue' },
                { label: '绿色', value: 'green' },
                { label: '红色', value: 'red' },
                { label: '青色', value: 'cyan' },
                { label: '自定义', value: '' },
              ]"></a-radio-group>
              <a-input v-model="customColor" @focus="handleFocus" style="width: 100px" placeholder="格式：#CC99FF">
              </a-input>
            </form-item>

            <form-item label="二维码模板上传" prop="qCodeTemplateUpload" v-if="qrcodeInfo.qrCodeStyle === '01'">
              <a-upload list-type="picture-card" :show-upload-list="false" :data="{ 'isup': 1 }"
                :before-upload="beforeUpload" :customRequest="templateImgUpload">
                <div v-if="this.templateImageUrl !== ''">
                  <img :src="this.templateImageUrl" width="100px" height="100px">
                  <a-tooltip placement="bottom">
                    <template slot="title">
                      <span>查看大图</span>
                    </template>
                    <a-icon :type="'eye'" theme="twoTone" twoToneColor="#4a9ff5" @click="viewTemplateImg" />
                  </a-tooltip>
                  <a-tooltip placement="bottom">
                    <template slot="title">
                      <span>清除图片</span>
                    </template>
                    <a-icon :type="'delete'" theme="twoTone" twoToneColor="#4a9ff5" @click="delTemplateImg" />
                  </a-tooltip>
                </div>
                <div v-if="this.templateImageUrl === ''">
                  <a-icon :type="'plus'" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </form-item>
            <form-item label="中心logo图片上传" v-if="qrcodeInfo.qrCodeStyle === '00' || qrcodeInfo.qrCodeStyle === '01'">
              <a-upload list-type="picture-card" :show-upload-list="false" :data="{ 'isup': 1 }"
                :before-upload="beforeUpload" :customRequest="logoImgUpload">
                <div v-if="this.licenceImageUrl !== ''">
                  <img :src="this.licenceImageUrl" width="100px" height="100px">
                  <a-tooltip placement="bottom">
                    <template slot="title">
                      <span>查看大图</span>
                    </template>
                    <a-icon :type="'eye'" theme="twoTone" twoToneColor="#4a9ff5" @click="viewLicenceImg" />
                  </a-tooltip>
                  <a-tooltip placement="bottom">
                    <template slot="title">
                      <span>清除图片</span>
                    </template>
                    <a-icon :type="'delete'" theme="twoTone" twoToneColor="#4a9ff5" @click="delLicenceImg" />
                  </a-tooltip>
                </div>
                <div v-if="this.licenceImageUrl === ''">
                  <a-icon :type="'plus'" />
                  <div class="ant-upload-text">上传</div>
                </div>
              </a-upload>
            </form-item>


            <!--            <div><p>温馨提示：点击“确定”后浏览器会自动下载二维码图片，请使用Firefox、chrom 浏览器</p></div>-->
            <div style="color: #f1545d">
              <p>温馨提示：模板只支持350*340、1024*1034两种分辨率，点击“保存”后浏览器</p>
              <p>会自动下载二维码图片，请使用Firefox、chrom 浏览器</p>
            </div>
          </entity-view>
        </div>
        <div class="qrcode-img" v-if="qrcodeInfo.qrCodeStyle === '00'">
          <div class="title">在此扫码付款</div>
          <div class="ima-wrapper" :class="[qrcodeInfo.colorStyle === 'green' ? 'green' : '', qrcodeInfo.colorStyle === 'blue' ? 'blue' : '',
          qrcodeInfo.colorStyle === 'red' ? 'red' : '', qrcodeInfo.colorStyle === 'cyan' ? 'cyan' : '']"
            :style="{ background: qrcodeInfo.colorStyle === '' ? customColor : '' }">
            <img class="img" :src="qrCodeData" alt="">
          </div>
        </div>
        <div class="qrcode-template" v-if="qrcodeInfo.qrCodeStyle === '01'">
          <div class="ima-wrapper">
            <img class="img" :src="templateQrCodeData" alt="">
          </div>
          <p>选择二维码模板，进行渲染二维码图片</p>
        </div>
      </div>
    </a-modal>
    <!--预览图片页面-->
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="this.imageUrl" />
    </a-modal>
  </base-view>
</template>

<script>
import EntityView from '../../../../components/common/entityView/EntityView.vue'
import FormItem from '../../../../components/common/entityView/FormItem.vue'
import { mapState } from "vuex"

export default {
  name: 'MerchantQRCode',
  components: { EntityView, FormItem },
  data: function () {
    return {
      beanInfo: {
        qrCodeNum: '',
      },
      exportOrViewTitle:'',
      exportOrViewOption:[],
      // 导出、详情 参数传递
      logoPath: '',
      imageLocalPath: '',
      applyBatchNo: '',
      qRcode: '',
      qrUrl: '页面所生成二维码为模拟数据，具体以导出文件为准',
      // 简洁版二维码渲染
      qrCodeData: '',
      // 整合版二维码渲染
      templateQrCodeData: '',
      templatePath: '',
      // 中心logo
      licenceImageUrl: '',
      previewVisible: false,
      imageUrl: '',
      // 二维码模板
      templateImageUrl: '',
      //
      qrcodeInfo: {},
      modalVisible: false,
      exportModalVisible: false,
      query: {
        instId: "",
      },
      loading: false,
      rules: { qrCodeNum: [{ required: true, message: '请输入生成二维码数量', trigger: 'blur' }] },
      patchColumns: [
        {
          title: '二维码类型',
          dataIndex: 'qrCodeType',
          width: 120
        },
        {
          title: '批次号',
          dataIndex: 'qrCodeBatchNo',
          width: 150
        },
        {
          title: '状态',
          dataIndex: 'qrCodeBatchStatus',
          customRender(text) {
            return text ? ['非正式', '正式', '停用', '已注销'][+text] : ''
          },
          width: 120
        },
        {
          title: '生成数量',
          dataIndex: 'qrCodeSum',
          width: 120
        },
        {
          title: '生成时间',
          dataIndex: 'createTime',
          width: 120
        }
      ],
      rowClick: (record, index) => ({
        on: {
          click: () => {
            this.selectedRowKeys = [];
            this.selectedRowKeys.push(index);
            this.selectedInfo = this.batchDataSource[index];
            this.searchDtl(record)
          }
        }
      }),
      batchDataSource: [],
      patchPagination: {
        size: 'small',
        pageNum: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `共${Math.ceil(total / this.pagination.pageSize)}页, ${total} 条记录`
      },
      pagination: {
        size: 'small',
        pageNum: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `共${Math.ceil(total / this.pagination.pageSize)}页， ${total} 条记录`
      },
      columns: [
        {
          title: '机构标识',
          dataIndex: 'instId',
          width: 120,
        },
        {
          title: 'logo路径',
          dataIndex: 'logoUrlPath',
          width: 150,
          ellipsis: true,
        },
        {
          title: '二维码物料编号',
          dataIndex: 'materialNo',
          width: 150,
          ellipsis: true,

        },
        {
          title: '二维码编号',
          dataIndex: 'qrNum',
          width: 120,
          ellipsis: true,
        },
        {
          title: '二维码URL',
          dataIndex: 'qrUrl',
          width: 300,
          ellipsis: true,
        },
        {
          title: '二维码代码',
          dataIndex: 'qrCode',
          width: 120,
          ellipsis: true,
        },
        {
          title: '二维码状态',
          dataIndex: 'qrStatus',
          width: 120,
          customRender(text) {
            return text ? ['正常', '停用'][+text] : ''
          }
        },
        {
          title: '绑定状态',
          dataIndex: 'bindStatus',
          width: 120,
          customRender(text) {
            return text ? ['未绑定', '已绑定'][+text] : ''
          }
        },
        {
          title: '内部商户号',
          dataIndex: 'mchntNo',
          width: 150
        },
        {
          title: '商户名称',
          dataIndex: 'merNameCh',
          width: 120
        },
        {
          title: '操作',
          fixed: 'right',
          scopedSlots: { customRender: 'operation' },
          width: 150
        }
      ],
      customRow: [],
      dataSource: [],
      customColor: '',
      selectedRowKeys: [],
      selectedInfo: {},
    }
  },
   computed: {
    ...mapState({
      currentUser: state => state.account.user
    })
  },
  methods: {
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/bmp'
      if (!isJPG) {
        this.$message.error('请上传图片文件');
      }
      return isJPG;
    },
    async templateImgUpload({ action, file, onSuccess, onError, onProgress }) {
      const formData = new FormData();
      formData.append('imgFile', file);
      // 二维码模板04 中心logo 03
      formData.append('imageType', "04");
      formData.append('instId', this.query.instId);
      const res = await this.$upload(
        "/admin/mcmp/bMchntImageInfo/uploadBomp", formData
      );
      if (res.data.code === "100000") {
        debugger
        // 请求参数赋值
        this.templatePath = res.data.data.imageLocalPath;
        // this.applyBatchNo = this.selectedInfo.qrCodeBatchNo
        //
        this.templateImageUrl = res.data.data.imageData;

        // 渲染二维码模板
        await this.getQRcodeByFile();
        this.$message.success("上传成功！");
        return true;
      } else {
        this.$message.error(res.data.data.respDesc);
        return false;
      }
    },
    async logoImgUpload({ action, file, onSuccess, onError, onProgress }) {
      const formData = new FormData();
      formData.append('imgFile', file);
      // 二维码模板04 中心logo 03
      formData.append('imageType', "03");
      formData.append('instId', this.query.instId);
      const res = await this.$upload(
        "/admin/mcmp/bMchntImageInfo/uploadBomp", formData
      );
      if (res.data.code === "100000") {
        // 请求参数赋值
        this.logoPath = res.data.data.imageLocalPath;
        this.applyBatchNo = this.selectedInfo.qrCodeBatchNo
        // 将logo图片路径保存到二维码信息表
        this.setUrl(this.query.instId, this.qRcode, this.applyBatchNo, res.data.data.imageLocalPath)
        //
        this.licenceImageUrl = res.data.data.imageData;
        this.$message.success("上传成功！");
        return true;
      } else {
        this.$message.error(res.data.data.respDesc);
        return false;
      }
    },
    viewLicenceImg(e) {
      this.imageUrl = this.licenceImageUrl;
      this.previewVisible = true;
      e.stopPropagation();
    },

    delLicenceImg(e) {
      this.licenceImageUrl = "";
      // this.$set(this.signInfo, 'licenceImage', null)
      e.stopPropagation();
    },
    viewTemplateImg(e) {
      this.imageUrl = this.templateImageUrl
      this.previewVisible = true;
      e.stopPropagation();
    },

    delTemplateImg(e) {
      this.templateImageUrl = "";
      e.stopPropagation();
    },
    handleCancel() {
      this.previewVisible = false;
    },
    async reset() {
      this.query.instId= ''
      this.patchPagination.pageNum = this.patchPagination.defaultCurrent;
      this.patchPagination.pageSize = this.patchPagination.defaultPageSize;
      this.selectedRowKeys = []
      this.dataSource = []
      this.pagination.total = 0;     
      if (!this.currentUser.admin) {
        // this.$set(this.query, "instId", this.currentUser.instId)
        this.query.instId = this.currentUser.instId;
        console.log("qqq", this.query, this.currentUser)
        await this.search();
      }
    },
    async search(e) {
      e && e.preventDefault && e.preventDefault()
      try {
        const res = await this.$get('/admin/merParam/qrcode/list', {
          instId: this.query.instId,
          qrCodeBatchNo: this.query.qrCodeBatchNo,
          // qrCodeType: this.query.qrCodeType,
          // qrStatus: this.query.qrStatus,
          pageNum: this.patchPagination.pageNum,
          pageSize: this.patchPagination.pageSize
        })
        this.batchDataSource = res.data.rows
        this.$set(this.patchPagination, 'total', +res.data.total)
      } catch (e) {
        console.error(e)
      }
    },
    async searchDtl(record) {
      try {
        const res = await this.$get('/admin/merParam/qrcode/listDtl', {
          instId: this.query.instId,
          qrCodeBatchNo: record.qrCodeBatchNo,
          qrCodeType: record.qrCodeType,
          pageNum: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        })
        this.dataSource = res.data.rows
        this.$set(this.pagination, 'total', +res.data.total)
      } catch (e) {
        console.error(e)
      }
    },
    async confirmSubmit(e) {
      try {
        const confirm = await this.$refs.modalForm.validate()
        if (confirm) {
          const res = await this.$post('/admin/merParam/qrcode/batchQrcode', {
            instId: this.query.instId,
            qrCodeNum: this.beanInfo.qrCodeNum,
            qrCodeType: 'IGAS'
          });
          console.log(res);
          if (res.data.code === '100000') {
            this.modalVisible = false;
            this.$message.success(res.data.message);
          } else {
            this.$message.error(res.data.message);
          }
          this.search()
        }
      } catch (e) {
        console.error(e)
      }
    },
    async changeStatus(record, optFlag) {
        if(record.bindStatus==='00'){
          this.$message.error('请先绑定商户')
          return
        }
        try {
        const res = await this.$post('/admin/merParam/qrcode/qrcodeManager', {
          instId: record.instId,
          qrCode: record.qrCode,
          qrCodeType: record.qrCodeType,
          optFlag: optFlag
        });
        if (res.status === 200) {
          this.$message.success("修改成功");
        }
        record.qrCodeBatchNo = record.applyBatchNo;
        this.searchDtl(record)
      } catch (e) {
        console.error(e)
      }
    },
    async exportBatch(record) {
      try {
        const res = await this.$get('/admin/merParam/qrcode/exportBatch', {
          instId: record.instId,
          applyBatchNo: record.qrCodeBatchNo,
          qrCodeType: record.qrCodeType,
          qrStatus: record.qrCodeBatchStatus
        });
        if (res.status === 200) {
        }
      } catch (e) {
        console.error(e)
      }
    },
    openModal() {
      this.modalVisible = true
      this.$refs.modalForm && this.$nextTick(this.$refs.modalForm.resetFields)
    },

    exportExcel() {
      if (this.selectedRowKeys.length === 0) {
        this.$message.warning("请先选择一条记录");
        return false;
      }
      this.qRcode='页面所生成二维码为模拟数据，具体以导出文件为准'
      this.exportBatch(this.selectedInfo)
      // 初始化导出页面，渲染二维码
      this.getQRcode()
      // 默认选中
      this.$set(this.qrcodeInfo, 'qrCodeStyle', "00");
      this.$set(this.qrcodeInfo, 'imgResolution', "00");
      this.$set(this.qrcodeInfo, 'colorStyle', "blue");
      //
      this.exportModalVisible = true;
      this.exportOrViewTitle='二维码批量导出'
      this.exportOrViewOption=[{ label: '简洁版', value: '00' },{ label: '整合版', value: '01' },{ label: '纯URL', value: '03' }]
    },
    // 查看二维码
    view(record) {
      this.qRcode=record.qrCode
      this.exportBatch(this.selectedInfo)
      // 初始化导出页面，渲染二维码
      this.getQRcode()
      // 默认选中
      this.$set(this.qrcodeInfo, 'qrCodeStyle', "00");
      this.$set(this.qrcodeInfo, 'imgResolution', "00");
      this.$set(this.qrcodeInfo, 'colorStyle', "blue");
      this.exportModalVisible = true;
      this.exportOrViewTitle='二维码查看'
      this.exportOrViewOption=[{ label: '简洁版', value: '00' },{ label: '整合版', value: '01' }]
    },

    pageChange(e) {
      this.pagination.pageNum = e.current;
      this.pagination.pageSize = e.pageSize;
      this.searchDtl(this.selectedInfo);
    },
    patchPageChange(e) {
      this.patchPagination.pageNum = e.current;
      this.patchPagination.pageSize = e.pageSize;
      this.search();
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedInfo = this.batchDataSource[selectedRowKeys[0]];
      this.searchDtl(this.selectedInfo)
    },
    async submitQRCode() {
      debugger;
      if (this.qrcodeInfo.qrCodeStyle === '01' && !this.templatePath) {
        this.$message.error('请先上传二维码模板');
        return;
      }
      let applyBatchNo = this.selectedInfo.qrCodeBatchNo
      let qrCodeType = this.selectedInfo.qrCodeType
      let instId = this.selectedInfo.instId
      let qrStatus = this.selectedInfo.qrCodeBatchStatus
      let tempPath = "";
      let exportUrl = false;

      if (this.qrcodeInfo.qrCodeStyle === '03') {
        // 导出纯URL
        exportUrl = true;
        try {
          // this.$export
          const res = await this.$export('/admin/merParam/qrcode/exportBatchs', {
            instId: instId,
            applyBatchNo: applyBatchNo,
            qrCodeType: qrCodeType,
            templatePath: tempPath,
            exportUrl: exportUrl
          });
          if (res.status === 200) {
          }
        } catch (e) {
          console.error(e)
        }
        /*url = WEB_ROOT + '/admin/merParam/qrcode/exportBatchs?applyBatchNo=' + applyBatchNo +
          "&qrCodeType=" + qrCodeType + "&instId=" + instId +
          "&templatePath=" + tempPath + "&exportUrl=" + exportUrl;
        window.open(url);*/
      } else {
        if (this.qrcodeInfo.qrCodeStyle === '01') {
          tempPath = this.templatePath;
        }
        try {
          const res = await this.$get('/admin/merParam/qrcode/exportBatchs', {
            instId: instId,
            applyBatchNo: applyBatchNo,
            qrCodeType: qrCodeType,
            templatePath: tempPath,
            exportUrl: exportUrl
          });
          if (res.status === 200) {
            let dateTime = res.message;
            this.getQrcodeImage(3000, dateTime, instId);
          }
        } catch (e) {
          console.error(e)
        }
        /*$.ajax({
          dataType: "json",
          method: "get",
          url: WEB_ROOT + '/admin/merParam/qrcode/exportBatchs?applyBatchNo=' + applyBatchNo +
            "&qrCodeType=" + qrCodeType + "&instId=" + instId +
            "&templatePath=" + tempPath + "&exportUrl=" + exportUrl,
          data: {},
          async: false,
          success: function (d) {
            if (d.type && d.type == "success") {
              Global.notify("success", "二维码批量导出异步处理中，请耐心等待");
              var dateTime = d.message;
              getQrcodeImage(3000, dateTime, instId);
            } else {
              Global.notify("error", "导出失败");
            }
          },
          error: function (XMLHttpRequest, textStatus, errorThrown) {

          }
        });*/
      }

      /*bootbox.dialog({
        closeButton: true, message: '确定导出该批次二维码吗？',
        title: '导出', buttons: {
          danger: {
            label: "取消", className: "btn-default",
            callback: function () {
            }
          },
          main: {
            label: "确认", className: "blue", callback: function () {
              var applyBatchNo = $('#qrcodeMateriel #applyBatchNo').val();
              var qrCodeType = $('#qrcodeMateriel #qrCodeType').val();
              var instId = $('#qrcodeMateriel #instId').val();
              var qrStatus = $('#qrcodeMateriel #qrStatus').val();
              var tempPath = "";
              var exportUrl = false;
              if ($('input[name=qrCodeStyle]:checked').val() == '03') {
                // 导出纯URL
                exportUrl = true;
                url = WEB_ROOT + '/admin/merParam/qrcode/exportBatchs?applyBatchNo=' + applyBatchNo +
                  "&qrCodeType=" + qrCodeType + "&instId=" + instId +
                  "&templatePath=" + tempPath + "&exportUrl=" + exportUrl;
                window.open(url);
              } else {
                if ($('input[name=qrCodeStyle]:checked').val() == '01') {
                  tempPath = templatePath;
                }
                $.ajax({
                  dataType: "json",
                  method: "get",
                  url: WEB_ROOT + '/admin/merParam/qrcode/exportBatchs?applyBatchNo=' + applyBatchNo +
                    "&qrCodeType=" + qrCodeType + "&instId=" + instId +
                    "&templatePath=" + tempPath + "&exportUrl=" + exportUrl,
                  data: {},
                  async: false,
                  success: function (d) {
                    if (d.type && d.type == "success") {
                      Global.notify("success", "二维码批量导出异步处理中，请耐心等待");
                      var dateTime = d.message;
                      getQrcodeImage(3000, dateTime, instId);
                    } else {
                      Global.notify("error", "导出失败");
                    }
                  },
                  error: function (XMLHttpRequest, textStatus, errorThrown) {
                    if (XMLHttpRequest.responseJSON) {
                      Global.notify("error", XMLHttpRequest.responseJSON.message);
                    } else {
                      Global.notify("error", "操作失败");
                    }
                  }
                });
              }
              $('#qrcodeMateriel #qrCodeCancelBtn').click();
            }
          }
        }
      });*/
    },
    getQrcodeImage(timeObj, dateTimeObj, instIdObj) {
      let $this = this;
      setTimeout(function () {
        if ($this.isExport("batchQrcodeImageFlag")) {
          try {
            // this.$export
            const res = $this.$get('/admin/merParam/qrcode/exportBatchs', {
              dateTime: dateTimeObj,
              instId: instIdObj,
            });
            if (res.status === 200) {
            }
          } catch (e) {
            console.error(e)
          }
          // url = WEB_ROOT + '/admin/merParam/qrcode/exportBatchs?dateTime=' + dateTimeObj + "&instId=" + instIdObj;
          // window.location.href = url;
        } else {
          this.getQrcodeImage(5000, dateTimeObj, instIdObj);
        }
      }, timeObj);
    },
    async isExport(exportKey) {
      let isClick = false;
      try {
        const res = await this.$post('/admin/merParam/qrcode/isExport', {
          exportKey: exportKey,
        });
        if (res.status === 200) {
          isClick = true;
        }
      } catch (e) {
        isClick = true;
        console.error(e)
      }
      return isClick;
    },
    handleFocus() {
      // 背景色，选中自定义选项
      this.qrcodeInfo.colorStyle = '';
    },
    async getQRcode() {
      try {
        const res = await this.$get('/admin/merParam/qrcode/getQRcode', {
          QRSuffix: this.qrUrl,
          qrCode: this.qRcode,
          logoPath: '',
          logoUrlPath: this.logoPath,
        })
        // 以base64数据填充src
        this.qrCodeData = res.data
      } catch (e) {
        console.error(e)
      }
    },
    async getQRcodeByFile() {
      try {
        const res = await this.$get('/admin/merParam/qrcode/getQRcodeByFile', {
          QRSuffix: '页面所生成二维码为模拟数据，具体以导出文件为准',
          templatePath: this.templatePath,
          logoPath: this.logoPath,
        })
        this.templateQrCodeData = res.data
      } catch (e) {
        console.error(e)
      }
    },
    async setUrl(instId, qRcode, applyBatchNo, imageLocalPath) {
      try {
        const res = await this.$post('/admin/merParam/qrcode/setUrl', {
          instId: instId,
          qRcode: qRcode,
          applyBatchNo: applyBatchNo,
          imageLocalPath: imageLocalPath
        });
        if (res.status === 200) {
          // 渲染右侧二维码
          if (this.qrcodeInfo.qrCodeStyle === "01" && this.templatePath) {
            await this.getQRcodeByFile();
            // var url = "${ctx}/admin/merParam/qrcode/getQRcodeByFile?QRSuffix=${requestScope.qrUrl}&time=<%=System.currentTimeMillis()%>&templatePath=" + templatePath + "&logoPath=" + param.imageLocalPath;
            // $('#qrcodeMateriel #qrCodeTemplateSrc').attr('src', encodeURI(encodeURI(url)));
          } else {
            await this.getQRcode();
          }
        }
      } catch (e) {
        console.error(e)
      }
    },
  },
}
</script>

<style scoped lang="scss">
.section {
  background: #fff;
}

.select {
  width: 180px;
}

.btn-group {
  margin-bottom: 20px;
}

.modal {
  display: flex;

  .form-wrapper {}

  .qrcode-img {
    min-width: 300px;
    height: 440px;
    border: 1px solid #f0f0f0;
    ;
  }

  .qrcode-img .title {
    font-size: 24px;
    color: #fff;
    padding: 12px;
    text-align: center;
    height: 60px;
    border-bottom: 1px solid #f0f0f0;
    background-color: #0ea9ee
  }

  .qrcode-img .ima-wrapper {
    height: calc(100% - 60px);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .qrcode-img .ima-wrapper.blue {
    background-color: #0ea9ee;
  }

  .qrcode-img .ima-wrapper.green {
    background-color: rgb(0, 128, 0);
  }

  .qrcode-img .ima-wrapper.red {
    background-color: rgb(255, 0, 0);
  }

  .qrcode-img .ima-wrapper.cyan {
    background-color: cyan;
  }

  .qrcode-img .ima-wrapper .img {
    width: 200px;
    height: 200px;
  }

  .qrcode-template .ima-wrapper {
    width: 300px;
    height: 380px;
    border: 1px solid #f0f0f0;
  }

  .qrcode-template .ima-wrapper .img {
    width: 100%;
    height: 100%;
  }

  .qrcode-template p {
    margin-top: 10px;
    text-align: center;
    color: red;
  }
}
</style>
